package com.ray.system.service.compose;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Long incr(String key, long liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.incrementAndGet();
        //初始设置过期时间
        if ((null == increment || increment.longValue() == 0) && liveTime > 0) {
            entityIdCounter.expire(liveTime, TimeUnit.SECONDS);
        }
        return increment;
    }

    public Long get(String key) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.get();
        return increment;
    }

    public Long getNext(String key) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.incrementAndGet();
        return increment;
    }

    public String getValue(String key) {
        return stringRedisTemplate.boundValueOps(key).get();
    }

    public void removeValue(String key) {
         stringRedisTemplate.delete(key);
    }

    public void setValue(String key,String value,long time) {
         stringRedisTemplate.boundValueOps(key).set(value,time,TimeUnit.SECONDS);
    }

    public void setValue(String key,String value,long time,TimeUnit unit) {
        stringRedisTemplate.boundValueOps(key).set(value,time,unit);
    }

}
